package com.itchu.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itchu.common.domain.PageResult;
import com.itchu.common.exption.ExceptionEnum;
import com.itchu.common.exption.MusicException;
import com.itchu.system.domain.Singer;
import com.itchu.system.domain.Song;
import com.itchu.system.mapper.SingerMapper;
import com.itchu.system.mapper.SongMapper;
import com.itchu.system.service.SongService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SongServiceImpl implements SongService {

    @Autowired
    private SongMapper songMapper;
    @Autowired
    private SingerMapper singerMapper;

    /**
     * 查找歌曲的分页信息
     * @param key   搜索条件
     * @param page  当前页
     * @param rows  页大小
     * @param sortBy
     * @param desc
     * @return
     */
    @Override
    public PageResult<Song> showAll(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //开启分页
        PageHelper.startPage(page,rows);
        //创建一个封装条件的对象
        Example example = new Example(Song.class);
        //判断搜索条件是否有值
        if (!StringUtils.isEmpty(key)) {
            Example.Criteria criteria = example.createCriteria();
            criteria.orLike("name","%"+key+"%");
        }
        //setOrderByClause 可以拼接sql语句
        if (!StringUtils.isEmpty(sortBy)) {
            example.setOrderByClause(sortBy +" "+ (desc ? "DESC" : "ASC"));
        }

        // 只显示审核通过的歌曲
        example.createCriteria().andEqualTo("state",'0');
        List<Song> list = songMapper.selectByExample(example);
        List<Singer> singers = singerMapper.selectAll();
        list.stream().forEach(song -> {
            singers.stream().forEach(singer -> {
                if (song.getSingerId().equals(singer.getId())) {
                    song.setSinger(singer);
                }
            });
        });
        PageInfo<Song> pageInfo = new PageInfo<>(list);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(),list);
    }

    /**
     * 添加歌曲操作
     * 添加的同时，不要忘记操作歌曲_分类中间表
     * @param song   歌曲对象
     * @param cids  分类ids
     * @return
     */
    @Override
    public void addSong(Song song, List<Long> cids) {
        if (song == null) {
            throw new RuntimeException("歌曲为空");
        }
        if (CollectionUtils.isEmpty(cids)) {
            throw new RuntimeException("风格为空");
        }
        //1.保存歌曲信息
        song.setCount(0);
        song.setCreateTime(new Date());
        song.setUpdateTime(new Date());
        songMapper.insert(song);
        Long sid = song.getId();
        //2.向歌曲-分类表这个中间表添加记录
        songMapper.delSongIdAndCategoryIdBySid(sid);
        songMapper.addSongIdAndCategoryId(sid,cids);

    }

    /**
     * 更新歌曲操作
     * @param song  歌曲对象
     * @param cids  分类ids
     * @return
     */
    @Override
    public void updateSong(Song song, List<Long> cids) {
        if (song == null) {
            throw new RuntimeException("歌曲为空");
        }
        if (CollectionUtils.isEmpty(cids)) {
            throw new RuntimeException("风格为空");
        }

        song.setUpdateTime(new Date());
        songMapper.updateByPrimaryKeySelective(song);

        Long sid = song.getId();

        //2.向歌曲-分类表这个中间表添加记录
        songMapper.delSongIdAndCategoryIdBySid(sid);
        songMapper.addSongIdAndCategoryId(sid,cids);

    }

    /**
     * 根据排行榜查询歌曲
     * @param type   1,是飙升榜    2，人气榜      3，收藏榜
     * @return
     */
    @Override
    public List<Song> findRankSongs(Long type) {
        List<Song> list = null;
        if (type != null) {
            if (type.equals(1L)) {
                //飙升榜
                list = songMapper.findSoar();
            }
            else if (type.equals(2L)) {
                //人气榜
                list = songMapper.findPopularity();
            }
            else if (type.equals(3L)) {
                //收藏榜
                // SELECT s.*,COUNT(sc.song_id) num FROM song s LEFT JOIN song_collect sc ON s.id = sc.song_id GROUP BY s.id ORDER BY num DESC LIMIT 0,15;
                list = songMapper.findFavorite();
            }

            List<Singer> singers = singerMapper.selectAll();
            list.stream().forEach(song -> {
                singers.stream().forEach(singer -> {
                    if (song.getSingerId().equals(singer.getId())) {
                        song.setSinger(singer);
                    }
                });
            });
        }
        return list;
    }

    /**
     * 按名字做模糊搜索
     * @param name
     * @return
     */
    @Override
    public List<Song> findSonsBySnameAndSiname(String name) {

        List<Song> list = songMapper.findSonsBySnameAndSiname(name);


        if (CollectionUtils.isEmpty(list)) {
            throw new MusicException(ExceptionEnum.MUSIC_NOT_SONGS);
        }
        return list;
    }

    /**
     * 删除歌曲操作
     * @param id  歌曲id
     * @return
     */
    @Override
    public void deleteSong(Long id) {
        songMapper.delSongIdAndCategoryIdBySid(id);
        songMapper.deleteByPrimaryKey(id);
    }
}
